/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Button, Col, Form, Input, message, Row } from 'antd';
import type { Rule } from 'antd/lib/form';
import type { ConnectState } from '@/models/connect';
import request from '@/utils/request';
import styles from './index.less';
import { useSelector } from 'umi';
import { TypeLoginPage, openLink, tabList } from './_utils';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const LoginPage: React.FC<TypeLoginPage> = ({ type, name }) => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [showPass, setShowPass] = useState(false);
  const [errorText, setErrorText] = useState(false);
  const [tempText, setTempText] = useState('');
  const [tempPass, setTempPass] = useState('');
  const [btnText, setBtnText] = useState('');
  const tabItem = tabList.find((item) => item.key === type);

  useEffect(() => {
    if (tabItem?.pwd) {
      setShowPass(true);
      setBtnText('获取临时密码');
    } else if (type === 'yjy') {
      setBtnText('登录');
    } else {
      setShowPass(false);
      setBtnText('登录');
    }
  }, [type]);

  const requestCallBack = (res: any) => {
    const { code, data, msg } = res;
    if (code == 0) {
      message.success(msg);
      if (tabItem?.pwd) {
        setTempPass(data.pwd);
      } else {
        openLink(data.url);
      }
    } else {
      message.error(msg);
    }
  };

  const onSubmit = useCallback(
    (values: any) => {
      const { phone } = values;
      let url;
      switch (type) {
        case 'courier':
        case 'kbyz':
          request('/secretLogin/generate', {
            data: {
              phone,
              type: type == 'kbyz' ? 'yz' : 's',
            },
            method: 'POST',
          })
            .then((res: any) => {
              const { data, code, msg } = res;
              if (code == 0) {
                message.success(msg);
                setTempPass(data.pwd);
              } else {
                message.error(msg);
              }
            })
            .catch((err) => {
              message.error(err);
            });
          break;
        case 'city':
        case 'wdadmin':
        case 'zy':
        case 'yjy':
          url =
            type === 'city' || type === 'zy' || type === 'yjy'
              ? '/NewRetailSecretLogin/get_verification'
              : '/secretLogin/get_verification';
          request(url, {
            data: {
              account: phone,
              type,
            },
            method: 'POST',
          })
            .then((res) => {
              const { code, msg } = res;
              if (code == 0) {
                if (type === 'city') {
                  openLink(`https://city.kuaidihelp.com/Api/Courier/privateLogin?phone2=${phone}`);
                } else if (type === 'yjy') {
                  openLink(
                    `http://yikuaisaoplus.hehengjia.com/Api/Courier/privateLogin?phone2=${phone}`,
                  );
                } else if (type === 'zy') {
                  openLink(`http://gp.chinapostcnps.com/Api/Courier/privateLogin?phone2=${phone}`);
                } else {
                  openLink(
                    `https://wdadmin.kuaidihelp.com/account/signin?userAccount=${phone}&is_check=1`,
                  );
                }
                setErrorText(false);
                setTempText('');
              } else if (type === 'yjy') {
                setErrorText(true);
                setTempText(msg);
              } else {
                message.error(msg);
              }
            })
            .catch((err) => {
              message.error(err);
            });
          break;
        case 'jdk':
        case 'jdkjms':
        case 'jdkweb':
        case 'jdklss':
        case 'jdk_rider':
        case 'jdk_fn':
          request('/jdk/SecretLogin/generate', {
            data: {
              phone,
              type,
            },
            method: 'POST',
          }).then(requestCallBack);
          break;
        case 'vhome':
          request('/secretLogin/commonSecretVhomeLogin', {
            data: {
              phone,
            },
            method: 'POST',
          }).then(requestCallBack);
          break;
        case 'vhome_web':
          request('/secretLogin/commonSecretLogin', {
            data: {
              type,
              phone,
            },
            method: 'POST',
          }).then(requestCallBack);
          break;
        default:
          console.error(new Error(`缺少${type}配置`));
          break;
      }
    },
    [type],
  );

  const rules = useMemo(() => {
    const rule: Rule[] = [
      {
        required: true,
        message: '请输入账号',
      },
    ];
    if (type == 'city' || type == 'yjy') {
      rule.push({
        pattern: /^1[2-9]{1}[0-9]{1}\d{8}$/,
        message: '手机号码输入错误',
      });
    }
    return rule;
  }, [type]);

  return (
    <div className={styles.page}>
      <Form {...layout} className={styles.form} onFinish={onSubmit} validateTrigger='onSubmit'>
        <Row style={{ width: '100%' }} justify='space-between' gutter={[20, 0]}>
          <Col sm={20} xs={24}>
            <Form.Item label={`${name}账号`} name='phone' rules={rules}>
              <Input allowClear style={{ width: winSize === 'xs' ? 300 : '100%' }} />
            </Form.Item>
          </Col>
          <Col sm={4} xs={24}>
            <Button htmlType='submit' type='primary'>
              {btnText}
            </Button>
          </Col>
        </Row>
        <Row style={{ width: '100%' }}>
          <Col sm={19} xs={24}>
            {showPass ? (
              <Form.Item label='临时密码'>
                <div style={{ color: 'red' }}>
                  {tempPass}
                  {tempPass && '（两分钟内有效）'}
                </div>
              </Form.Item>
            ) : (
              errorText && (
                <Form.Item label='提示'>
                  <div style={{ color: 'red' }}>{tempText}</div>
                </Form.Item>
              )
            )}
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default LoginPage;
